<?php

namespace Amcolin\GiteeUpdate;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;

class GiteeUpdate extends Controller
{
    public function index(){
        //git webhook 自动部署脚本
        $savePath = str_replace('/app' , '' , app_path());
        $user = config('gitee.nginxUser');
        $group = config('gitee.userGroup');
        if (!$user){
            return 'not user';
        }
        if (!$group){
            return 'not group';
        }
        $password = config('gitee.password');
        if (!$password){
            return 'not pass';
        }
        $content = json_decode(file_get_contents("php://input") , true);
        if (empty($content)) {
            return 'not content';
        }
        //解析Git服务器通知过来的JSON信息
        if($content['password'] != $password){
            return 'password error';
        }
        //若是主分支且提交数大于0
        if (($content['ref'] == 'refs/heads/master' || $content['ref'] == 'refs/heads/test_version') && $content['total_commits_count'] > 0) {
            $chown = sprintf('chown -R %s:%s %s' , $user , $group , $savePath);
            exec($chown);
            $command = 'git pull 2>&1';
            exec($command , $res);
            $res_log = '----------------------' . PHP_EOL;
            $res_log .= $command . PHP_EOL;
            $res_log .= $content['user_name'] . ' 向' . $content['repository']['name'] . '项目的' . $content['ref'] . '分支push了' .$content['total_commits_count'] . '个commit：';
            foreach ($res as $val){
                $res_log .= $val . PHP_EOL;
            }
            Log::debug('gitUpdate log' , [$res_log]);
            return 'success';
        }
        return 'not found push info';
    }
}